﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using log4net;
using LapvWebComponent;
using LapvComponent;
using System.Configuration;
using LapvBussiness;

namespace Lapv.page
{
    public partial class NewsManager : System.Web.UI.Page
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(NewsManager).Name);
        public  int tid = 0;
        
        public string domain = ConfigurationManager.AppSettings["DomainNews"];

        protected void Page_Load(object sender, EventArgs e)
        {
           
           
            string urlReturn = this.Request.RawUrl.ToString();
            ProviderAdmin.CheckAuthen(urlReturn, 3);
            if(Page.IsPostBack) return;
            LoadCate();
            bindddlPaged();
            if (Request.Params["tid"] != null)
            {
                int.TryParse(Request.Params["tid"].Trim().Replace("'", ""), out tid);
                ddlCate.SelectedValue = tid.ToString();
                Session["cateid"] = ddlCate.SelectedValue;
                Session["statusid"] = ddlStatus.SelectedValue;
                pager1.CurrentIndex = 1; 
            } 
            LoadData();
        }
        void LoadCate()
        {
            try
            {
                List<news_category> lst = Provider.GetListNewsCate();
                if (lst != null && lst.Count > 0)
                {
                    ddlCate.DataSource = lst;
                    ddlCate.DataTextField = "name";
                    ddlCate.DataValueField = "id";
                    ddlCate.DataBind();
                    ddlCate.Items.Insert(0, new ListItem("---Chọn loại tin---", "0"));

                }
            }
            catch (Exception ex)
            {
                 log.Error(ex.Message + "--" + ex.Source + "--" + ex.InnerException);
                ((Lapv)this.Master).MessageError = "Đã xảy ra lỗi. " + ex.Message;
                
            }
        }
        void LoadData()
        {
            try
            {
                using (lapvwebEntities db = new lapvwebEntities())
                {
                    List<news> lst=null;
                    int cateid=-1;
                    int statusid = 0;
                    if (Session["cateid"] != null)
                        ddlCate.SelectedValue = Session["cateid"].ToString();
                    if(ddlCate.SelectedValue!=null && ddlCate.SelectedValue!="")
                        cateid=int.Parse(ddlCate.SelectedValue);
                    if (Session["statusid"] != null)
                        ddlStatus.SelectedValue = Session["statusid"].ToString();
                    if (ddlStatus.SelectedValue != null && ddlStatus.SelectedValue != "")
                        statusid = int.Parse(ddlStatus.SelectedValue);
                    lst = db.news.Include("news_category").ToList();
                    if (statusid >= 0)
                        lst = lst.Where(ec=>ec.status==statusid).ToList();
                    if (cateid > 0)
                        lst = lst.Where(ec => ec.news_category.id == cateid).ToList();
                    int from = (pager1.CurrentIndex - 1) * pager1.PageSize;
                    pager1.ItemCount = lst.Count;
                    
                    if (pager1.ItemCount < from)
                    {
                        from = 0;
                    }


                    dtgrid.DataSource = lst.Skip(from).Take(pager1.PageSize);
                    dtgrid.DataBind();
                    

                }
            }
            catch (Exception ex)
            {
                
               log.Error(ex.Message + "--" + ex.Source + "--" + ex.InnerException);
                ((Lapv)this.Master).MessageError = "Đã xảy ra lỗi. " + ex.Message;
            }
 
        }
        //protected void Find(object sender, EventArgs e)
        //{
        //    LoadData();
        //}
       
        protected void ChangeSelectIndex(object sender, EventArgs e)
        {
            Session["cateid"] = ddlCate.SelectedValue;
            Session["statusid"] = ddlStatus.SelectedValue;
            pager1.CurrentIndex = 1;
            LoadData();
 
        }
        public void pager_Command(object sender, CommandEventArgs e)
        {
           int currnetPageIndx = Convert.ToInt32(e.CommandArgument);
           pager1.CurrentIndex = currnetPageIndx;
           LoadData();

        }
        protected void ddlPaged_SelectedIndexChanged(object sender, EventArgs e)
        {
            pager1.PageSize = Convert.ToInt32(ddlPaged.SelectedValue);
            pager1.CurrentIndex = 1;
            LoadData();

        }
        void bindddlPaged()
        {
            ddlPaged.Items.Insert(0, new ListItem("10", "10"));
            ddlPaged.Items.Insert(1, new ListItem("15", "15"));
            ddlPaged.Items.Insert(2, new ListItem("20", "20"));
            ddlPaged.Items.Insert(3, new ListItem("30", "30"));
            ddlPaged.Items.Insert(4, new ListItem("50", "50"));
            pager1.PageSize = 50;
            ddlPaged.SelectedValue = "50";
        }
        public string GetNameStatus(sbyte val)
        {
            string status = "";
            try
            {
                if (val > 0)
                {
                    switch (val)
                    {
                        case 0:
                            status = "Không dùng";
                            break;
                        case 1:
                            status = "Đang dùng";
                            break;
                        case 2:
                            status = "Chờ đăng";
                            break;

                        
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + "--" + ex.Source + "--" + ex.InnerException);
                ((Lapv)this.Master).MessageError = "Đã xảy ra lỗi. " + ex.Message;
                
            }
            return status;
        }
        public string GetAllowDelete(bool val)
        {
            string name = "";
            try
            {
                
                    if (val == true)
                        name = "<img src=\"../styles/imgs/checkmark.png\">";
                    else name = "";
                
            }
            catch (Exception ex)
            {

                log.Error(ex.Message + "--" + ex.Source + "--" + ex.InnerException);
                ((Lapv)this.Master).MessageError = "Đã xảy ra lỗi. " + ex.Message;
            }
            return name;
        }
        protected void dtgrid_ItemDataBound(Object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.Header)
            {

                news ns = (news)e.Item.DataItem;
                if (ns != null)
                {
                    if (ns.allowdelete == false)
                    {
                        e.Item.Cells[8].CssClass = "hidden";
                    }
                    if (ns.status != 2)
                        e.Item.Cells[5].CssClass = "hidden";


                }

            }


        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            string msg = "";
            try
            {
                ImageButton imageButton = (ImageButton)sender;
                int newsId = int.Parse(imageButton.CommandArgument);
                if (newsId > 0)
                {
                    using (lapvwebEntities db = new lapvwebEntities())
                    {
                        news obj = db.news.Where(ec => ec.id == newsId && ec.allowdelete == true).FirstOrDefault();
                        if (obj != null)
                        {
                            db.DeleteObject(obj);
                            db.SaveChanges();
                            msg = "Xóa tin thành công. Mã tin: " + newsId;
                        }
                        else
                        {
                            msg = "Xóa tin bị lỗi. Mã tin: " + newsId + ". Do không tồn tại đối tượng";
                            ((Lapv)this.Master).MessageError = "Không tồn tại đối tượng cần xóa";
                        }
                    }

                }
                else
                {
                    msg = "Xóa tin bị lỗi. Mã tin: " + newsId + ". Do mã tin không phù hợp";
                    ((Lapv)this.Master).MessageError = "Mã tin muốn xóa không phù hợp";
                    return;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                msg = "Xóa tin bị lỗi. Mã tin: " + ID + ". Do " + ex.Message;
                ((Lapv)this.Master).MessageError = "Có lỗi xảy ra" + ex.Message;

            }
            try
            {
                int uid = 0;
                string uname = string.Empty;
                uid = ProviderAdmin.GetUsserId();
                if (Session["UserName"] != null)
                    uname = Session["UserName"].ToString();
                ProviderAdmin.AddLog(uid, uname, msg, string.Empty, "NEWS_DELETE");
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
            }
            LoadData();
        }
        public void functionGridNews(object source, DataGridCommandEventArgs evt)
        {
            int newsId = 0;
            switch (evt.CommandName.Trim().ToLower())
            {
                case "edit":
                    try
                    {
                        if (evt.CommandArgument.ToString() != null)
                        {
                            newsId = Convert.ToInt32(evt.CommandArgument);
                            Response.Redirect("NewsAdd.aspx?newsid=" + newsId.ToString());
                        }
                    }
                    catch (Exception)
                    {
                        return;
                    }
                    break;
                
               
            }

        }
       
    }
}
